import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * 18. 四数之和
 * https://leetcode.cn/problems/4sum/description/
 */
class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        Arrays.sort(nums);
        List<List<Integer>> ret = new LinkedList<>();
        int n = nums.length;
        for(int i = 0; i <= n - 4;) {
            int tmpA = target - nums[i];
            for(int j = i + 1; j <= n - 3;) {
                int tmpB = tmpA - nums[j];
                int left = j + 1, right = n - 1;
                while(left < right) {
                    if(nums[left] + nums[right] < tmpB) {
                        left++;
                        while(left < right && nums[left] == nums[left - 1]) {
                            left++;
                        }
                    } else if(nums[left] + nums[right] > tmpB) {
                        right--;
                        while(left < right && right + 1 < n && nums[right] == nums[right + 1]) {
                            right--;
                        }
                    } else {
                        ret.add(new LinkedList<>(Arrays.asList(nums[i], nums[j], nums[left], nums[right])));
                        left++;
                        right--;
                        while(left < right && nums[left] == nums[left - 1]) {
                            left++;
                        }
                        while(left < right && right + 1 < n && nums[right] == nums[right + 1]) {
                            right--;
                        }
                    }

                }
                j++;
                while(j < n && nums[j] == nums[j - 1]) j++;
            }
            i++;
            while(i < n && nums[i] == nums[i - 1]) i++;
        }

        return ret;
    }
}